import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getNewCategoryListApi, getNewsListApi } from '../../api/news';
import { getAllServiceAPI } from "../../api/find";

export const initialState = {
    count:1000,
    top:45,
    newsList:[],  // 新闻列表
    newCategoryList:[],  // 新闻分类列表 
    path:{
        fromPath:'',
        toPath:'',
    },
    address:null, // 所在城市信息 
    allServices:[], // 所有服务 
}

const dataSlice = createSlice({
    name:"dataSpace",
    initialState:initialState,
    reducers:{
        changeCount(state,{payload}){
            state.count+=payload
        },
        changePaddingTop(state,{payload}){
            state.top = payload;
        },
        changePath(state,{payload}){
            state.path = payload;
        },
        changeAddress(state,{payload}){
            state.address = payload; 
        }
    },
    extraReducers:(builder:any)=>{
        builder
        .addCase(getNewCategoryList.fulfilled,(state:any,action:any)=>{
            console.log(action)
            state.newCategoryList = action.payload;
        })
        .addCase(getNewsList.fulfilled,(state:any,action:any)=>{
            state.newsList = action.payload;
        })
        .addCase(getAllService.fulfilled,(state:any,action:any)=>{
            state.allServices = action.payload;
        })
    }
})

export const{
    changeCount,
    changePaddingTop,
    changePath,
    changeAddress
} = dataSlice.actions

export const data_count = (state:any) => state.MyData.count
export const data_top = (state:any) => state.MyData.top
export const data_newCategoryList = (state:any)=>state.MyData.newCategoryList;
export const data_newsList = (state:any)=>state.MyData.newsList;
export const data_path = (state:any)=>state.MyData.path;
export const data_allServices = (state:any)=>state.MyData.allServices;
export const data_address = (state:any)=>state.MyData.address;



export const getNewCategoryList:any = createAsyncThunk('dataSpace/newCategoryList',async (callback?:any)=>{
    let res:any = await getNewCategoryListApi()
    console.log(res.data);
    
    callback(res.data[0])
    return res.data;
})

export const getNewsList:any = createAsyncThunk('dataSpace/newsList',async (params?:any)=>{
    let res:any = await getNewsListApi(params)
    return res.rows;
})

export const getAllService:any = createAsyncThunk('dataSpace/getAllService',async (params?:any)=>{
    let res:any = await getAllServiceAPI(params)
    return res.rows; 
})


export default dataSlice.reducer